<?php
class Resource {
	/**
	* @var mixed Mysql connection
	*/
	var $mysqli = null;
	/**
	* @var array User credentials (id, email, type)
	*/
	var $user = null;
	/**
	* @var array Notifications
	*/
	var $notif = array();
	/**
	* @var string Area of concentration
	*/
	var $area = 'rsrc';
	/**
	* @var string Database table to be used
	*/
	var $table = 'Resources';
	/**
	* @var mixed Options
	*/
	
	/**
	* Resource constructor
	* Initializes resource variables for intended request
	* 
	* @param string $area Area of concentration
	* @param resource $mysqli Current mysql connection
	* @param resource $user User credentials (id, email, type)
	*/
	function __construct($area, $mysqli, $user) {
		# Include all necessary classes
		require_once "class/setting.php";
		require_once "class/file.php";
		require_once "class/image.php";
		require_once "class/document.php";
		require_once "class/tool.php";
	
		$this->mysqli = $mysqli;
		$this->user = $user;
		$this->area = $area;
		
		switch($area) {
			# Microorganism
			case 'micro':
				$this->table = 'MicroRsrcs';
			break;
			
			# Project
			case 'proj':
				$this->table = 'ProjRsrcs';
			break;
			
			# Links
			case 'link':
				$this->table = 'RsrcLinks';
			break;
			
			# Images
			case 'img':
				$this->table = 'ImgRsrcs';
			break;
			
			# Document
			case 'doc':
				$this->table = 'DocRsrcs';
			break;
			
			# Location
			case 'loc':
				$this->table = 'LocRsrcs';
			break;
			
			# Marked microorganisms
			case 'mark-micro':
				$this->table = 'MarkMicros';
			break;
			
			# Marked resources
			case 'mark-rsrc':
				$this->table = 'MarkRsrcs';
			break;
		}
	}
	
	/**
	* Search resource
	* Searches for a resource based on
	* query string, optional paramaters as constraints,
	* start and end line of result in a mysql resource
	* 
	* @access public
	* @param string $query Keyword/s to look for in the database
	* @param array $opts Contains constraints in search (category, order, author, etc.)
	* @param integer $start Beginning line of searched keyword in mysql resource
	* @param integer $limit End of returned mysql resource as a result of search
	* 
	* @return array Mixed result from mysql query and size of returned rows
	*/
	public function search($query, $opts, $start, $limit) {
		$query = is_array($query) ? $query : Tool::trimout($query);
		$selSize = "SELECT FOUND_ROWS()";
		
		# Search based on ID
		if($opts["c"]=="id" or $opts["c"]=="view") {
			$query = empty($opts['id']) ? $query : $opts['id'];
			
			$sel = "
				SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Resources AS T1 WHERE T1.ID='{$query}' ".(in_array($this->user['type'], array('ADMIN','PRIME')) ? '' : " T1.Remove='0' AND ")."
					AND ('{$this->user['type']}'='PRIME' OR T1.Visib='PUB' OR (T1.Visib='PRV' AND (T1.CrtBy='{$this->user['id']}'
					OR (SELECT COUNT(*) FROM RsrcCoeds AS T2 WHERE T2.PID='{$query}' AND T2.CID='{$this->user['id']}') > 0)))
				ORDER BY T1.Title
			";
		}
		else {
			$cond = "";
			
			# Break down query string to words
			if(!is_array($query)) $arrQuery = explode(" ", Tool::trimout($query));
			
			# Ordering
			$opts["ob"] = isset($opts["ob"]) ? $opts['ob'] : "Title";
			$opts["oa"] = isset($opts["oa"]) ? $opts["oa"] : "ASC";
			
			# Category
			if(isset($opts['c'])) {
				switch($opts["c"]) {
					# Images
					case "img-tile":
						$this->table = "Marks";
						
						$sel = "
							SELECT SQL_CALC_FOUND_ROWS * FROM Marks
								WHERE ImgID='{$query}'
							ORDER BY CrtOn LIMIT {$start}, 10
						";
					break;
					
					# Marks
					case "mark":
						$sel = "
							SELECT SQL_CALC_FOUND_ROWS * FROM {$opts["t"]}
								WHERE PID='{$query[1]}'
							ORDER BY CrtOn LIMIT {$start}, 10
						";
					break;
					
					# Microorganisms
					case "micro":
						$categ = "
							INNER JOIN MicroRsrcs AS T3 INNER JOIN Microorganisms AS T4
								ON T1.ID=T3.CID AND T3.PID=T4.ID
							WHERE T4.ID='{$query}' OR T4.Name LIKE '%{$query}%' OR T4.Notes LIKE '%{$query}%'
						";
					break;
					
					# Images
					case "img":
						$categ = "
							INNER JOIN ImgRsrcs AS T3 INNER JOIN Images AS T4
								ON T1.ID=T3.CID AND T3.PID=T4.ID
							WHERE T4.ID='{$query}' OR T4.Title LIKE '%{$query}%' OR T4.Notes LIKE '%{$query}%'
						";
					break;
					
					# Documents
					case "doc":
						$categ = "
							INNER JOIN DocRsrcs AS T3 INNER JOIN Documents AS T4
								ON T1.ID=T3.CID AND T3.PID=T4.ID
							WHERE T4.ID='{$query}' OR T4.Title LIKE '%{$query}%' OR T4.Notes LIKE '%{$query}%'
						";
					break;
					
					# Locations
					case "loc":
						$categ = "
							INNER JOIN LocRsrcs AS T3 INNER JOIN Locations AS T4
								ON T1.ID=T3.CID AND T3.PID=T4.ID
							WHERE T4.ID='{$query}' OR T4.Name LIKE '%{$query}%' OR T4.Notes LIKE '%{$query}%'
						";
					break;
					
					# Projects
					case "proj":
						$categ = "
							INNER JOIN ProjRsrcs AS T3 INNER JOIN Projects AS T4
								ON T1.ID=T3.CID AND T3.PID=T4.ID
							WHERE T4.ID='{$query}' OR T4.Title LIKE '%{$query}%' OR T4.Abstr LIKE '%{$query}%'
						";
					break;
					
					# Multiple ids
					case "multi-id":
						$categ = "WHERE T1.ID IN ('".implode("','", $query)."')";
					break;
					
					case 'title':
					case 'notes':
						# Title, notes
						$cond .= " (T1.Title LIKE '%{$query}%' OR T1.Notes LIKE '%{$query}%') AND ";
					break;
				}
			}
			
			# Included words/phrase
			if(!empty($opts["i"])) {
				$cond .= " (T1.Title LIKE '%{$opts["i"]}%' OR T1.Notes LIKE '%{$opts["i"]}%') AND ";
			}
			
			# Excluded words/phrase
			if(!empty($opts["e"])) {
				$arrQuery = explode(", ", $opts["e"]);
				$title = "T1.Title NOT LIKE '%".implode("%' OR T1.Title NOT LIKE '%", $arrQuery)."%'";
				$notes = "T1.Notes NOT LIKE '%".implode("%' OR T1.Notes NOT LIKE '%", $arrQuery)."%'";
				$cond .= " ({$title} AND {$notes}) AND ";
			}
			
			# Creator
			if(!empty($opts["cb"])) {
				if(empty($opts['cbi'])) {
					$name = explode(", ", $opts["cb"]);
					
					# Account name
					if(count($name)==3) {
						list($lname, $fname, $mi) = $name;
						$cond .= " (T1.CrtBy IN (SELECT ID FROM Accounts WHERE Lname='".Tool::trimout($lname)."'AND Fname='".Tool::trimout($fname)."') AND ";
					}
					# Email
					else if(strrpos($opts['cb'], '@') > 1) {
						$cond .= " (T1.CrtBy IN (SELECT ID FROM Accounts WHERE Email='{$opts['cb']}')) AND ";
					}
					# Other
					else {
						$cond .= "(T1.CrtBy='%{$query}%') AND ";
					}
				}
				# Account ID
				else {
					$cond .= " (T1.CrtBy='{$opts['cbi']}') AND ";
				}
			}
			
			# Creation date
			if(!empty($opts['co']['s'])) {
				if(!empty($opts["co"]["e"])) {
					$cond .= " (T1.CrtOn BETWEEN '".Tool::trimout($opts["co"]["s"])."' AND '".Tool::trimout($opts["co"]["e"])."') AND ";
				}
				else {
					$cond .= " (T1.CrtOn='".Tool::trimout($opts["co"]["s"])."') AND ";
				}
			}
			
			# Name
			if(empty($opts["c"]) or ($opts["c"]=="title" and !empty($query))) {
				$cond .= " (T1.Title LIKE '%{$query}%') AND ";
			}
			
			$cond .= (in_array($this->user['type'], array('ADMIN','PRIME')) and $opts['c']=='remove') ? " T1.Remove='1' AND " : " T1.Remove='0' AND ";
			
			# Limit of returned rows
			$range = (isset($start) and !empty($limit)) ? "LIMIT {$start}, {$limit}" : '';
			
			if(empty($categ)) {
				$cond = "
					WHERE {$cond} (T1.Visib='PUB' OR ('{$this->user['type']}'='PRIME')
						OR (T1.Visib='PRV' AND (T1.CrtBy='{$this->user['id']}'
						OR (SELECT COUNT(T2.CID) FROM ImgCoeds AS T2 WHERE T2.PID=T1.ID AND T2.CID='{$this->user['id']}') > 0)))
				";
			}
			else {
				$cond = "
					{$categ} AND {$cond} (T1.Visib='PUB' OR ('{$this->user['type']}'='PRIME')
						OR (T1.Visib='PRV' AND (T1.CrtBy='{$this->user['id']}'
						OR (SELECT COUNT(T2.CID) FROM ImgCoeds AS T2 WHERE T2.PID=T1.ID AND T2.CID='{$this->user['id']}') > 0)))
				";
			}
			
			$sel = "
				SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Resources AS T1 {$cond} ORDER BY T1.{$opts["ob"]} {$opts["oa"]} {$range}
			";
		}
		
		# Search resource
		$res = $this->mysqli->query($sel);
		$size = $this->mysqli->query($selSize);
		$size = $size->fetch_row();
		
		# Return results and size of results
		return array($res, $size[0]);
	}
	
	/**
	* Create resource
	* Create a new resource
	* 
	* @access public
	* @param string $title Title
	* @param string $notes Additional information
	* @param array $links Hyperlinks on the web
	* @param array $files Images, documents
	* @param array $coeds Coeditors
	* @param string $categ Category
	* @param string $visib Visibility
	* 
	* @return mixed ID on success, false on failure
	*/
	public function create($title, $notes, $links, $refs, $files, $coeds, $categ, $visib) {
		$id = Tool::generateID('rsrc');
		
		# Insert query
		$ins = "
			INSERT INTO Resources VALUES (
				'{$id}', '{$categ}', '{$visib}', '{$title}', '{$notes}', NULL, NULL,
				'".(empty($coeds["val"]) ? 0 : count($coeds["val"]))."',
				NULL, NULL, '0', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."', '0'
			)
		";
		
		# Create resource in database
		if($this->mysqli->query($ins)) {
			# Append links
			if(!empty($links)) {
				$this->appendLink($id, $links);
			}
			
			# Append files
			if(!empty($files['name'])) {
				$file = new File('rsrc', $this->mysqli, $this->user);
				$file->append($files, $id, $categ, $visib);
			}
			
			# Append coeditors
			if(!empty($coeds['val'])) {
				$edtr = new Editor('rsrc', $this->mysqli, $this->user);
				$edtr->append($coeds, $id, false);
			}
		}
		# Error creating resource
		else {
			$this->notif = "ERROR: insert rsrc";
		}
		
		# Successfully created resource
		if(empty($this->notif)) {
			return $id;
		}
		
		# Error occurred
		//echo '<pre>', var_dump($this->notif), '</pre>';
		return false;
	}
	
	/**
	* Update resource
	* Update an existing resource on the system
	* 
	* @access public
	* @param string $id Resource ID
	* @param string $title Title
	* @param string $notes Additional information
	* @param array $links Hyperlinks/URLs
	* @param array $pic Primary photo
	* @param array $imgs Images
	* @param array $docs Documents
	* @param array $files Images, documents
	* @param array $coeds Coeditors
	* @param string $categ Category
	* @param string $visib Visibility
	* @param array $rlinks Links to be removed
	* @param array $rimgs Images to be removed
	* @param array $rdocs Documents to be removed
	* @param array $rcoeds Coeditors to be removed
	* 
	* @return boolean True on success, false on failure
	*/
	public function update(
		$id, $title, $notes, $links, $refs, $pic, $imgs, $docs, $files, $coeds, $categ, $visib,
		$rlinks, $rimgs, $rdocs, $rcoeds
	) {
		# Update string
		$upd = "
			UPDATE Resources SET
				Categ='{$categ}', Visib='{$visib}',
				Title='{$title}', Notes='{$notes}', ".(empty($pic) ? '' : "ImgPath='{$pic}',")."
				UpdBy='{$this->user['id']}', UpdOn='".date('Y-m-d H:i:s:ms')."', UpdNo=UpdNo+1
			WHERE ID='{$id}'
		";
		
		# Update resource in database
		if($this->mysqli->query($upd)) {
			# Append links
			if(!empty($links)) {
				$this->appendLink($id, $links);
			}
			
			# Remove links
			if(!empty($rlinks)) {
				$this->removeLink($id, $rlinks);
			}
			
			# Operate on images
			$img = new Image('rsrc', null, $this->mysqli, $this->user);
			$img->operate($imgs, $rimgs, $id);
			
			# Operate on documents
			$doc = new Document('rsrc', array('id'=>$id), $this->mysqli, $this->user);
			$doc->operate($docs, $rdocs, $id);
			
			# Append files
			if(!empty($files['name'])) {
				$file = new File('rsrc', $this->mysqli, $this->user);
				$file->append($files, $id, $categ, $visib);
			}
			
			# Operate on coeditors
			$coed = new Editor('rsrc', $this->mysqli, $this->user);
			$coed->operate($coeds, $rcoeds, $id, false);
		}
		# Error updating resource
		else {
			$this->notif[] = "ERROR: edit rsrc <br/>";
		}
		
		# Update resource successfully
		if(empty($this->notif)) {
			return true;
		}
		
		# Error updating resource
		//echo '<pre>', var_dump($this->notif), '</pre>';
		return false;
	}
	
	/**
	* Delete resource
	* Delete an existing resource from the system
	* 
	* @access public
	* @param string $id Resource ID
	* 
	* @return boolean True on success, false on failure
	*/
	public function delete($id) {
		$del = "UPDATE Resources SET Remove='1' WHERE ID='{$id}'";
		
		# Delete from database
		if(!$this->mysqli->query($del)) {
			return false;
		}
	}
	
	/**
	* Recover resource
	* Recover a deleted resource
	* 
	* @access public
	* @param string $id Resource ID
	* 
	* @return boolean true on success, false on failure
	*/
	public function recover($id) {
		# Query string to recover resource
		$del = "UPDATE Resources SET Remove='0' WHERE ID='{$id}'";
		
		# Recover resource in the database
		$res = $this->mysqli->query($del);
		
		# Error occurred in deletion
		if(!$res) {
			echo "ERROR: recover";
			return false;
		}
		
		# Successfully recovered resource
		return true;
	} # function recover
	
	/**
	* Process appended and remove resources
	* Process on all resources associated with an area
	* which are to be appended or removed
	* 
	* @access public
	* @param array $addl Resources to be appended
	* @param array $rmvl Resources to be removed
	* @param string $id ID of area
	*/
	public function operate($addl, $rmvl, $id) {
		if(!empty($addl["val"])) $this->append($addl, $id);
		if(!empty($rmvl)) $this->remove($rmvl, $id);
	}
	
	/**
	* Append resources
	* Append resources associated to that area
	* 
	* @access public
	* @param array $addl Resources to be appended
	* @param string $id ID of area
	*/
	public function append($addl, $id) {
		# Iterate through each resource
		foreach($addl['val'] as $i => $title) {
			if(empty($title)) continue;
			
			$ins = '';
			
			# Append using resource ID
			if(!empty($addl['id'][$i])) {
				$ins = "INSERT INTO {$this->table} VALUES ('{$id}', '{$addl['id'][$i]}', '1', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
			}
			else {
				# Search resource
				$res = $this->mysqli->query("SELECT ID FROM Resources WHERE Title='{$title}'");
				
				# Resource found
				if($res and !empty($res->num_rows)) {
					$obj = $res->fetch_object();
					$ins = "INSERT INTO {$this->table} VALUES ('{$id}', '{$obj->ID}', '1', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
				}
			}
			
			# Append resource to area
			if(!empty($ins)) {
				if(!$this->mysqli->query($ins)) {
					$this->notif[] = "ERROR: ins area-rsrc {$id} $value.<br/>";
				}
			}
		}
	}
	
	/**
	* Remove resources
	* Remove resources associated to that area
	* 
	* @access public
	* @param array $rmvl Resources to be removed
	* @param string $id ID of area
	*/
	public function remove($rmvl, $id) {
		$del = "DELETE FROM {$this->table} WHERE PID='{$id}' AND CID IN ('".implode("', '", $rmvl)."')";
		
		# Remove assoc. resources
		if(!$this->mysqli->query($del)) {
			$this->notif[] = "ERROR: rem micro<br/>";
		}
	}
	
	/**
	* Mark image
	* Marks an image
	* 
	* @access public
	* @param boolean $new True, create mark; false, update mark
	* @param string $id ID of image
	* @param array $info Information about the mark
	* @param array $coords Upperleft coordinates of mark
	* @param array $size Height and width of mark
	* @param string $path Path to image
	* @param integer $height Height of staged image
	* @param string $title Title
	* @param string $notes Additional info
	* @param string $categ Category
	* @param string $visib Visibility
	*
	* @return boolean True on success, false on failure
	*/
	public function mark($new, $upload, $id, $info, $coords, $size, $path, $height, $title, $notes, $ref, $categ, $visib) {
		# Create new marked image
		if($new) {
			list($id, $dstImgID, $path) = $this->markImg($id, $title, $notes, $ref, $path, $coords, $size, $height, $categ, $visib);
		}
		# Update mark
		else {
			$dstImgID = $id;
		}
		
		# ID of appended mark
		$markID = $this->appendMark($id, $dstImgID, $coords, $size);
		
		# Microorganism to be marked
		if($this->area=='mark-micro') {
			$this->markMicros($info, $markID, $id, $new, $upload, $categ, $visib);
		}
		elseif($this->area=='mark-img') {
			$this->markImgs($info, $markID, $id, $new, $upload, $categ, $visib);
		}
		# Resource to be marked
		elseif($this->area=='mark-rsrc' ) {
			$this->markRsrc($info, $markID, $id, $path, $categ, $visib);
		}
		
		# Successfully marked image
		if(empty($this->notif)) {
			return true;
		}
		
		# Error occurred
		//echo '<pre>', var_dump($this->notif), '</pre>';
		return false;
	}
	
	/**
	* Mark part of image
	* Create a part of the image as a mark
	* 
	* @access public
	* @param string $id ID of image
	* @param string $title Title of mark
	* @param string $Notes Notes about mark
	* @param string $path Path to image
	* @param array $coords Upperleft coordinates of mark
	* @param array $size Height and width of mark
	* @param integer $height Height of staged image
	* @param string $categ Category
	* @param string $visib Visibility
	*
	* @return array Mark image ID, Source image ID, Source image path
	*/
	public function markImg($id, $title, $notes, $ref, $path, $coords, $size, $height, $categ, $visib) {
		# Get dimensions of image
		list($owidth, $oheight) = getimagesize($path);
		# Calculate dimensions of mark
		$dx = 1000/$owidth;
		$dy = $height/$oheight;
		$x = $coords[0]/$dx;
		$y = $coords[1]/$dy;
		$width = $size[0]/$dx;
		$height = $size[1]/$dy;
		
		# Get extension of image
		$ext = substr($path, strrpos($path, '.'));
		
		# Filename of mark
		$filepath = 'data/tmp/'.uniqid($this->user['id'].'-').$ext;
		
		# Create image resource
		$imgp = imagecreatetruecolor($width, $height);
		
		switch($ext) {
			# JPEG
			case '.jpg':
			case '.jpeg':
				# Create image from jpeg mark
				# Resize and copy
				$img = imagecreatefromjpeg($path);
				imagecopy($imgp, $img, 0, 0, $x, $y, $owidth, $oheight);
				imagejpeg($imgp, $filepath, 100);
				$type = 'image/jpeg';
			break;
			
			# GIF
			case '.gif':
				# Create image from gif mark
				# Resize and copy
				$img = imagecreatefromgif($path);
				imagecopy($imgp, $img, 0, 0, $x, $y, $owidth, $oheight);
				imagegif($imgp, $filepath);
				$type = 'image/gif';
			break;
		}
		
		# Destroy image resources
		imagedestroy($img);
		imagedestroy($imgp);
		
		# Update source image and set to scene
		$this->mysqli->query("UPDATE Images SET Scene='1' WHERE ID='{$id}'") or die();
		
		# Search source image
		$sel = "SELECT * FROM Images WHERE ID='{$id}'";
		$res = $this->mysqli->query($sel);
		
		# Image found
		if($res and !empty($res->num_rows)) {
			# Get source image
			$srcimg = $res->fetch_object();
			$title = empty($title) ? $srcimg->Title : $title;
			
			# Create new image
			$img = new Image('mark', array(
				'id'=>$id, 'path'=>$srcimg->Dir,
				'src'=>$srcimg->Src, 'srcid'=>$srcimg->SrcID,
				'scn'=>$srcimg->Scene, 'blk'=>$srcimg->Block,
			), $this->mysqli, $this->user);
			$imgID = $img->create(
				array('name'=>$title.$ext, 'type'=>$type, 'size'=>filesize($filepath), 'tmp_name'=>$filepath, 'error'=>0),
				$title, empty($notes) ? null : $notes, empty($ref) ? null : $ref, null, null, null, null, null, $categ, $visib
			);
			
			# Successfully created image
			if(isset($imgID) and $imgID!=false) {
				$sel = "SELECT * FROM Images WHERE ID='{$imgID}'";
				
				if($res = $this->mysqli->query($sel)) {
					$img = $res->fetch_object();
					
					# Remove temporary file
					if(file_exists($filepath)) {
						unlink($filepath);
					}
					
					# Return mark ID, source image ID and path to source image
					return array($imgID, $id, $img->Path);
				}
				else {
					$this->notif[] = 'ERROR: sel new mark img';
				}
			}
		}
		else {
			$this->notif[] = 'ERROR: sel orig mark img';
		}
		
		# Return default mark ID
		return array(null, $id, $path);
	}
	
	/**
	* Mark with microorganisms
	* Mark an image with microorganisms
	* 
	* @access public
	* @param array $micros Microorganisms to be marked
	* @param string $markID ID of mark
	* @param string $dstImgID ID of image
	* @param string $new If true, create new mark
	* @param string $categ Category
	* @param string $visib Visibility
	*/
	public function markMicros($micros, $markID, $dstImgID, $new, $upload, $categ, $visib) {
		# There are microorganisms to be marked
		if(!empty($micros['val'])) {
			# Array, meaning many microorganisms are to be marked
			if(is_array($micros['val'])) {
				# Iterate through each microorganisms
				foreach($micros['val'] as $i => $name) {
					# Mark with microorganism
					$this->markMicro(
						array(
							'val'=>$name, 'code'=>$micros['code'][$i], 'auth'=>$micros['auth'][$i],
							'note'=>$micros['note'][$i], 'id'=>$micros['id'][$i]
						), $markID, $dstImgID, $new, $upload, $categ, $visib
					);
				}
			}
			else {
				# Mark with microorganism
				$this->markMicro($micros, $markID, $dstImgID, $new, $upload, $categ, $visib);
			}
		}
	}
	
	/**
	* Mark with images
	* Mark an image with additional images
	* 
	* @access public
	* @param array $imgs Images to be marked
	* @param string $markID ID of mark
	* @param string $dstImgID ID of image
	* @param string $new If true, create new mark
	* @param string $categ Category
	* @param string $visib Visibility
	*/
	public function markImgs($imgs, $markID, $dstImgID, $new, $upload, $categ, $visib) {
		# There are microorganisms to be marked
		if(!empty($imgs['val'])) {
			# Array, meaning many microorganisms are to be marked
			if(is_array($imgs['val'])) {
				# Iterate through each microorganisms
				foreach($imgs['val'] as $i => $title) {
					# Mark with microorganism
					$this->markImage(
						array(
							'val'=>$title, 'note'=>empty($imgs['note'][$i]) ? null : $imgs['note'][$i],
							'id'=>empty($imgs['id'][$i]) ? null : $imgs['id'][$i]
						), $markID, $dstImgID, $new, $upload, $categ, $visib
					);
				}
			}
			else {
				# Mark with microorganism
				$this->markImage($imgs, $markID, $dstImgID, $new, $upload, $categ, $visib);
			}
		}
	}
	
	/**
	* Mark with microorganism
	* Mark an image with a microorganism
	* 
	* @access public
	* @param array $micro Microorganism to be marked
	* @param string $markID ID of mark
	* @param string $dstImgID ID of image
	* @param string $new If true, create new mark
	* @param string $categ Category
	* @param string $visib Visibility
	*
	* @param boolean True on success, false on failure
	*/
	public function markMicro($micro, $markID, $dstImgID, $new, $upload, $categ, $visib) {
		if(empty($micro['id'])) {
			# Search microorganism
			$sel = "SELECT * FROM Microorganisms WHERE Name='{$micro['val']}' LIMIT 1";
			
			# Microorganism is found
			if(($resMicro = $this->mysqli->query($sel)) and !empty($resMicro->num_rows)) {
				$smicro = $resMicro->fetch_object();
				$micro['id'] = $smicro->ID;
			}
			# Create new microorganism
			elseif($new) {
				$micro['id'] = Tool::generateID('micro');
				
				# Create new microorganism query string
				$ins = "
					INSERT INTO Microorganisms VALUES (
						'{$micro['id']}', '{$categ}', '{$visib}', '{$micro['val']}', "
						.(empty($micro['code']) ? 'NULL' : "'{$micro['code']}'").", "
						.(empty($micro['auth']) ? 'NULL' : "'".mysql_real_escape_string($micro['auth'])."'").", "
						.(empty($micro['note']) ? 'NULL' : "'".mysql_real_escape_string($micro['note'])."'").", "
						.(empty($micro['ref']) ? 'NULL' : "'".mysql_real_escape_string($micro['ref'])."'").", 
						NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0,
						NULL, NULL, 0, NULL, NULL, 0, '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."', '0'
					)
				";
				
				# Error occurred
				if(!$this->mysqli->query($ins)) {
					$this->notif[] = 'ERROR: ins new micro mark<br/>';
				}
			}
		}
		
		# Append mark with microorganism ID
		if(!empty($micro['id'])) {
			$ins = "INSERT INTO MarkMicros VALUES ('{$markID}', '{$dstImgID}', '{$micro['id']}', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
			
			# Append mark
			if($this->mysqli->query($ins)) {
				$sel = "SELECT * FROM Microorganisms WHERE ID='{$micro['id']}'";
				
				# Search microorganism
				if($res = $this->mysqli->query($sel)) {
					$micro = $res->fetch_object();
					
					# Search image
					$sel = "SELECT * FROM Images WHERE ID='{$dstImgID}'";
					
					# Display mark data
					if($res = $this->mysqli->query($sel)) {
						$img = $res->fetch_object();
						
						if(!$upload) {
							# Get settings of image
							$sett = new Setting('img', null, $this->mysqli, $this->user); ?>
							
							<output style="display:none">
								<output id="thumb">
									<var id="markid"><?php echo $markID ?></var>
									<var id="imid"><?php echo $dstImgID ?></var>
									<var id="id"><?php echo $micro->ID ?></var>
									<var id="src"><?php echo $img->Path ?></var>
								</output> <?php
								
								if(!$new) { ?>
									<output id="micro">
										<div class="micro area mark" data-id="<?php echo $micro->ID ?>" data-markid="<?php echo $id ?>" data-title="<?php echo $micro->Name ?>">
											<div class="div-peel peel next off open"><b><?php echo Tool::truncate($micro->Name, 50) ?></b></div>
											<div class="div-case mark" style="margin-bottom:50px">
												<form class="edit-mark">
													<div class="left" style="width:100px;margin-right:5px">
														<a href="main.php?micro=view&id=<?php echo $micro->ID ?>" target="_blank">
															<img src="<?php echo !file_exists($micro->ImgPath) ? 'template/micro.jpg' : $micro->ImgPath ?>" alt="<?php $micro->Name ?>" class="preview ghost"/></a>
													</div>
													
													<div>
														<a href="main.php?micro=view&id=<?php echo $micro->ID ?>"><i><?php echo $micro->Name ?></i></a> <?php
														# If creator or prime, display remove
														if(!empty($this->user['id']) and ($sett->verify($dstImgID) or $this->user['type']=='PRIME')) { ?>
															<button type="button" class="mark-remove micro icon" data-area="micro"></button> <?php
														} ?>
														<div class="small dim" data-tool="{'head':'<b>Notes</b>','body':'<?php echo $micro->Notes ?>','behav':'More','stay':1}"><?php echo Tool::truncate($micro->Notes, 250 - strlen($micro->Name)) ?></div>
													</div>
												</form>
											</div>
										</div>
									</output> <?php
								} ?>
							</output> <?php
						}
						
						return true;
					}
					# Error in getting image
					else {
						$this->notif[] = "insert micro-mark 3 <br/>";
						return false;
					}
				}
				# Error in getting microorganism
				else {
					$this->notif[] = "insert micro-mark 2 <br/>";
					return false;
				}
			}
			# Error in appending mark
			else {
				$this->notif[] = "insert micro-mark 1 <br/>";
			}
		}
		
		# Error occurred
		echo "<output>ERROR:<hr/>{$this->notif}</output>";
		return false;
	}
	
	/**
	* Mark with image
	* Mark an image with another image
	* 
	* @access public
	* @param array $img Image to be marked
	* @param string $markID ID of mark
	* @param string $dstImgID ID of image
	* @param string $new If true, create new mark
	* @param string $upload If image is uploaded or not
	* @param string $categ Category
	* @param string $visib Visibility
	*
	* @param boolean True on success, false on failure
	*/
	public function markImage($img, $markID, $dstImgID, $new, $upload, $categ, $visib) {
		$sel = "SELECT * FROM Images WHERE ID='{$img['id']}'";
		
		if($res = $this->mysqli->query($sel)) {
			$img = $res->fetch_object();
			$ins = "INSERT INTO MarkImgs VALUES ('{$markID}', '{$dstImgID}', '{$img->ID}', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
			$sett = new Setting('img', null, $this->mysqli, $this->user);
			
			# Append as a mark
			if(!$this->mysqli->query($ins)) {
				$this->notif[] = "Error adding resources to mark";
			}
			else { ?>
				<output style="display:none">
					<output id="thumb">
						<var id="markid"><?php echo $markID ?></var>
						<var id="imid"><?php echo $dstImgID ?></var>
						<var id="id"><?php echo $img->ID ?></var>
						<var id="src"><?php echo $img->Path ?></var>
					</output>
					
					<output id="img"> <?php
						if(!$new) { ?>
							<span class="mark area" data-markid="<?php echo $id ?>" data-id="<?php echo $img->ID ?>" data-title="<?php echo $img->Title ?>">
								<a href="main.php?img=view&id=<?php echo $img->ID ?>" class="thumb">
									<img src="<?php echo $img->Thumb ?>" alt="<?php echo $img->Title ?>" data-imid="<?php echo $img->ID ?>" data-src="<?php echo $img->Path ?>"
										data-tool="{'head':'<div><?php echo $img->Title;
											if(!empty($this->user['id']) and $sett->verify($dstImgID)) { ?> &nbsp;
												<button type=\'button\' class=\'mark-remove icon\' data-area=\'img\' data-title=\'<?php echo $img->Title ?>\'></button> <?php
											} ?>
										</div><hr/><small><?php echo Tool::truncate($img->Notes, 150) ?> <a href=\'main.php?img=view&id=<?php echo $img->ID ?>\' target=\'_blank\'>Read more</a></small>','x':'l','stay':1}"
									class="file ghost left" style="height:100px;width:<?php echo intval((100/$img->Height)*$img->Width) ?>px"/></a>
							</span> <?php
						} ?>
					</output>
				</output> <?php
				
				return true;
			}
		}
		else {
			$this->notif[] = "Image is not found";
		}
		
		return false;
	}
	
	/**
	* Mark with resource
	* Mark an image with a resource
	* 
	* @access public
	* @param array $rsrc Resouce to be marked
	* @param string $markID ID of mark
	* @param string $dstImgID ID of image
	* @param string $new If true, create new mark
	* @param string $categ Category
	* @param string $visib Visibility
	*
	* @param boolean True on success, false on failure
	*/
	public function markRsrc($rsrc, $markID, $dstImgID, $dstImgPath, $categ, $visib) {
		# Create resource
		$id = $this->create($rsrc['title'], $rsrc['notes'], empty($rsrc['link'][0]) ? null : $rsrc['link'], empty($rsrc['ref'][0]) ? null : $rsrc['ref'], null, null, 'BSC', 'PUB');
		
		# Created successfully
		if(!empty($id)) {
			$ins = "INSERT INTO MarkRsrcs VALUES ('{$markID}', '{$dstImgID}', '{$id}', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
			
			# Append as a mark
			if(!$this->mysqli->query($ins)) {
				$this->notif[] = "Error adding resources to mark";
			}
		}
		
		# Marked successfully
		if(empty($this->notif)) { ?>
			<output style="display:none">
				<var id="markid"><?php echo $markID ?></var>
				<var id="imid"><?php echo $dstImgID ?></var>
				<var id="id"><?php echo $id ?></var>
				<var id="src"><?php echo $dstImgPath ?></var>
			
				<div class="rsrc area mark" data-id="<?php echo $id ?>" data-markid="<?php echo $markID ?>" data-title="<?php echo $rsrc['title'] ?>">
					<div class="div-peel peel next off"><b><?php echo Tool::truncate($rsrc['title'], 50) ?></b></div>
					<div class="div-case mark">
						<form class="edit-mark">
							<textarea name="title" class="title read reqd" readonly="readonly" placeholder="Title" rows="<?php echo ceil(strlen($rsrc['title'])/50) ?>"><?php echo $rsrc['title'] ?></textarea></br>
							<textarea name="notes" placeholder="Notes" class="notes read reqd" readonly="readonly" rows="<?php echo ceil(strlen($rsrc['notes'])/25) ?>"><?php echo $rsrc['notes'] ?></textarea> <?php
							if(!empty($rsrc['link'][0])) { ?><br/>
								<a href="<?php echo $rsrc['link'][0] ?>"><?php echo $rsrc['link'][0] ?></a><br/> <?php
							} ?>
							
							<div class="div-mind">
								<input name="upd" type="checkbox" class="abled"/>
							</div>
							
							<button type="button" class="mark-remove rsrc none small" data-title="<?php echo $rsrc['title'] ?>" data-area="rsrc"> Remove</button>
							<button type="button" class="reset small mark-edit"><span>Edit</span></button>
							<button type="submit" class="none small">Save</button>
							<span class="notif small"></span>
						</form>
					</div>
				</div>
			</output> <?php
			
			return true;
		}
		
		echo "<output>ERROR:<hr/>{$this->notif}</output>";
		return false;
	}
	
	/**
	* Append mark
	* Add additional marks to an image
	* 
	* @access public
	* @param string $dstImgID ID of destination image
	* @param string $srcImgID ID of source image
	* @param array $coords Upperleft coordinate of mark in image
	* @param array $size Size of mark
	*
	* @param string Mark ID
	*/
	public function appendMark($dstImgID, $srcImgID, $coords, $size) {
		# Search for marks in an image
		$sel = "SELECT ID FROM Marks WHERE ImgID='{$dstImgID}' AND X='{$coords[0]}' AND Y='{$coords[1]}' AND Width='{$size[0]}' AND Height='{$size[1]}'";
		$resMark = $this->mysqli->query($sel);
		
		# Mark is already present
		if($resMark and !empty($resMark->num_rows)) {
			$mark = $resMark->fetch_object();
			$id = $mark->ID;
		}
		# Mark is not found
		else {
			$id = Tool::generateID('mark');
			
			# Create new mark
			$ins = "
				INSERT INTO Marks VALUES (
					'{$id}', '{$srcImgID}', '{$dstImgID}', '{$coords[0]}', '{$coords[1]}', '{$size[0]}', '{$size[1]}', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."', '0'
				)
			";
			
			# Error creating mark
			if(!$this->mysqli->query($ins)) {
				$this->notif = 'ERROR: append mark';
			}
		}
		
		# Return mark ID
		return $id;
	}
	
	/**
	* Append mark
	* Add additional marks to an image
	* 
	* @access public
	* @param string $id ID of destination image
	*
	* @param boolean True on success, false on failure
	*/
	public function draw($id) {
		# Find image
		$sel = "SELECT * FROM Marks WHERE ImgID='{$id}' AND Remove='0' ORDER BY CrtOn";
		
		# Image is found
		if($resMark = $this->mysqli->query($sel)) { ?>
			<map> <?php
				# Display all marks in that image
				while($mark = $resMark->fetch_object()) {
					if($resImg = $this->mysqli->query("SELECT * FROM Images WHERE ID='{$mark->ImgMarkID}'")) {
						$imgmark = $resImg->fetch_object(); ?>
						
						<div class="thumb mark" title="Click to zoom in" data-id="<?php echo $mark->ID ?>" data-imgid="<?php echo $mark->ImgID ?>" data-imid="<?php echo $mark->ImgMarkID ?>"
							data-coords="<?php echo $mark->X.",".$mark->Y ?>" data-size="<?php echo $mark->Width.",".$mark->Height ?>"
							data-src="<?php echo $imgmark->Path ?>"/><?php
					}
				} ?>
			</map> <?php
			
			return true;
		}
		# Image is not found
		else {
			echo "ERROR: Cannot draw image's marks";
			return false;
		}
	}
	
	/**
	* Focus mark
	* Show image details on a block
	* 
	* @access public
	* @param string $imgid ID of block image
	*
	* @param mixed String on success, false on failure
	*/
	public function focusMark($imgid) {
		# Select block from images
		$sel = "
			SELECT * FROM Images WHERE ID='$imgid' AND Remove='0'
		";
		
		if($imgs = $this->mysqli->query($sel)) {
			$img = $imgs->fetch_object();
			# Show block details ?>
			<span class="cool"><?php echo $img->Title ?></span><hr/>
			<div><?php echo $img->Notes ?></div> <?php
		}
		else {
			return false;
		}
	}
	
	/**
	* Focus microorganism
	* Display all microorganisms tagged on a block
	* 
	* @access public
	* @param string $id ID of block
	* @param string $imgid ID of image
	*
	* @param boolean True on success, false on failure
	*/
	public function focusMicro($id, $imgid) {
		# Find all microorganisms assoc. with mark
		$sel = "
			SELECT T1.* FROM Microorganisms AS T1 INNER JOIN MarkMicros AS T2
				ON T1.ID=T2.MicroID AND T2.PID='{$id}' AND T1.Remove='0'
			ORDER BY T2.CrtOn
		";
		
		$micros = $this->mysqli->query($sel);
		
		# Images are present
		if($micros and !empty($micros->num_rows)) {
			$i = 0;
			$sett = new Setting('img', null, $this->mysqli, $this->user);
			
			while($micro = $micros->fetch_object()) {
				$name = Tool::truncate($micro->Name, 100);
				$imgpath = (($empty = empty($micro->ImgPath)) ? 'template/micro.jpg' : $micro->ImgPath);
				list($ow, $oh) = getimagesize($imgpath); ?>
				
				<div class="micro area mark" data-id="<?php echo $micro->ID ?>" data-markid="<?php echo $id ?>" data-title="<?php echo $name ?>">
					<div class="div-peel peel next <?php echo $i==0 ? "off open" : "on" ?>"><b class="ital"><?php echo Tool::truncate($name, 50) ?></b></div>
					<div class="div-case mark <?php echo $i++==0 ? "" : "none" ?>" style="height:100px"> 
						<form class="edit-mark">
							<div class="left" style="width:100px;margin-right:5px">
								<a href="main.php?micro=view&id=<?php echo $micro->ID ?>" target="_blank">
									<img src="<?php echo $empty ? $imgpath : "process.php?img=crop&ow={$ow}&oh={$oh}&w=150&h=150&x=50&y=50&path={$imgpath}" ?>" alt="<?php echo $micro->Name ?>" class="ghost left"/></a>
							</div>
							
							<div>
								<a href="main.php?micro=view&id=<?php echo $micro->ID ?>"><i><?php echo $micro->Name ?></i></a> <?php
								if(!empty($this->user['id']) and $sett->verify($imgid)) { ?>
									<button type="button" class="mark-remove micro icon" data-area="micro"></button> <?php
								} ?>
								<div class="small dim" data-tool="{'head':'<b>Notes</b>','body':'<?php echo $micro->Notes ?>','stay':1,'behav':'More'}"><?php echo Tool::truncate($micro->Notes, 250 - strlen($micro->Name)) ?></div>
							</div>
						</form>
					</div>
				</div> <?php
			}
			
			return true;
		}
		# No microorganisms found
		else {
			echo "<label>No microorganisms found</label>";
			return false;
		}
	}
	
	/**
	* Focus image
	* Display all images linked in that mark
	* 
	* @access public
	* @param string $id ID of mark
	* @param string $imgid ID of image
	*
	* @param boolean True on success, false on failure
	*/
	public function focusImg($id, $imgid) {
		# Find all images assoc. with mark
		$sel = "
			SELECT T1.* FROM Images AS T1 INNER JOIN MarkImgs AS T2
				ON T1.ID=T2.ImgID2 AND T2.PID='{$id}' AND T1.Remove='0'
			ORDER BY T2.CrtOn
		";
		
		$imgs = $this->mysqli->query($sel);
		
		# Images are present
		if($imgs and !empty($imgs->num_rows)) {
			$i = 0;
			$sett = new Setting('img', null, $this->mysqli, $this->user);
			
			while($img = $imgs->fetch_object()) {
				$title = Tool::truncate($img->Title, 100);
				$thumb = ($empty = !file_exists($img->Path)) ? 'template/micro.jpg' : $img->Thumb;
				list($ow, $oh) = getimagesize($thumb); ?>
				
				<span class="mark area" data-markid="<?php echo $id ?>" data-id="<?php echo $img->ID ?>" data-title="<?php echo $img->Title ?>">
					<a href="main.php?img=view&id=<?php echo $img->ID ?>" class="thumb">
						<img src="<?php echo $thumb ?>" alt="<?php echo $img->Title ?>" data-imid="<?php echo $img->ID ?>" data-src="<?php echo $img->Path ?>"
							data-tool="{'head':'<div><?php
								echo $img->Title;
								if(!empty($this->user['id']) and $sett->verify($imgid)) { ?> &nbsp;
									<button type=\'button\' class=\'mark-remove icon\' data-area=\'img\' data-title=\'<?php echo $img->Title ?>\'></button> <?php
								} ?>
							</div><hr/><small><?php echo Tool::truncate($img->Notes, 150) ?> <a href=\'main.php?img=view&id=<?php echo $img->ID ?>\' target=\'_blank\'>Read more</a></small>','x':'l','stay':1}"
						class="file ghost left" style="height:100px;width:<?php echo intval((100/$img->Height)*$img->Width) ?>px"/></a>
				</span> <?php
			}
			
			return true;
		}
		# No images found
		else {
			echo "<label>No images found</label>";
			return false;
		}
	}
	
	/**
	* Focus resource
	* Display all resources present in that mark
	* 
	* @access public
	* @param string $id ID of mark
	* @param string $imgid ID of image
	*
	* @param boolean True on success, false on failure
	*/
	public function focusRsrc($id, $imgid) {
		# Find all resources assoc. with mark
		$sel = "
			SELECT T1.* FROM Resources AS T1 INNER JOIN MarkRsrcs AS T2
				ON T1.ID=T2.RsrcID AND T2.PID='{$id}' AND T1.Remove='0'
			ORDER BY T2.CrtON
		";
		
		$rsrcs = $this->mysqli->query($sel);
		
		# Images are present
		if($rsrcs and !empty($rsrcs->num_rows)) {
			$i = 0;
			$sett1 = new Setting('img', null, $this->mysqli, $this->user);
			$sett2 = new Setting('rsrc', null, $this->mysqli, $this->user);
			
			while($rsrc = $rsrcs->fetch_object()) { ?>
				<div class="rsrc area mark" data-id="<?php echo $rsrc->ID ?>" data-markid="<?php echo $id ?>" data-title="<?php echo $rsrc->Title ?>">
					<div class="div-peel peel next <?php echo $i==0 ? "off open" : "on" ?>"><b><?php echo Tool::truncate($rsrc->Title, 50) ?></b></div>
					<div class="div-case mark <?php echo $i++==0 ? "" : "none" ?>">
						<form class="edit-mark">
							<textarea name="title" class="title read reqd" readonly="readonly" placeholder="Title" data-tool="{'head':'Title','x':'l'}"
								rows="<?php echo ceil(strlen($rsrc->Title)/50) ?>"><?php echo $rsrc->Title ?></textarea></br>
							<textarea name="notes" placeholder="Notes" class="notes read reqd" readonly="readonly" data-tool="{'head':'Notes','x':'l'}"
								rows="<?php echo empty($rsrc->Notes) ? '5' : ceil(strlen($rsrc->Notes)/50) ?>"><?php echo $rsrc->Notes ?></textarea><br/> <?php
							
							list($resLink, $sizeLink) = $this->retrieve('link', $rsrc->ID);
							
							if(!empty($sizeLink)) { ?>
								<ol class="link"> <?php
									while($link = $resLink->fetch_object()) { ?>
										<li class="link">
											<a href="<?php echo $link->Link ?>" target="_blank"><?php echo Tool::truncate($link->Link, 70) ?></a>
											<button type="button" class="remove icon read" data-area="link" data-id="<?php echo $link->CID ?>"></button>
										</li> <?php
									} ?>
								</ol>
								<a class="fetch link tick small" data-area="link" data-id="<?php echo $rsrc->ID ?>" data-start="10">Show more</a> <?php
							}
							
							# Display controls if user is creator, or prime
							if(!empty($this->user['id']) and ($sett1->verify($imgid) or $sett2->verify($rsrc->ID))) { ?>
								<div class="div-mind">
									<input name="upd" type="checkbox" class="abled"/>
								</div>
								
								<button type="button" class="mark-remove rsrc none small" data-area="resource"> Remove</button>
								<button type="button" class="reset small mark-edit"><span>Edit</span></button>
								<button type="submit" class="none small">Save</button>
								<span class="notif small"></span> <?php
							} ?>
						</form>
					</div>
				</div> <?php
			}
			
			return true;
		}
		# No resources are found
		else {
			echo "<label>No resources found</label>";
			return false;
		}
	}
	
	/**
	* Remove marked microorganism
	* Remove microorganism in a mark
	* 
	* @access public
	* @param string $markID ID of mark
	* @param string $microID ID of microorganism
	*
	* @param mixed True on success, info on failure
	*/
	public function removeMicro($markID, $microID) {
		$del = "DELETE FROM MarkMicros WHERE PID='{$markID}' AND MicroID='{$microID}'";
		
		# Remove microorganism assoc. with mark 
		if(!$this->mysqli->query($del)) {
			$this->notif = "ERROR: delete micro-mark <br/>";
		}
		
		# Removed successfully
		if(empty($this->notif)) {
			return true;
		}
		
		# Error in removing
		return $this->notif;
	}
	
	/**
	* Remove marked resource
	* Remove resource in a mark
	* 
	* @access public
	* @param string $markID ID of mark
	* @param string $rsrcID ID of resource
	*
	* @param mixed True on success, info on failure
	*/
	public function removeRsrc($markID, $rsrcID) {
		$del = "DELETE FROM MarkRsrcs WHERE PID='{$markID}' AND RsrcID='{$rsrcID}'";
		
		# Remove resource assoc. with mark 
		if(!$this->mysqli->query($del)) {
			$this->notif = "ERROR: delete rsrc-mark <br/>";
		}
		
		# Removed successfully
		if(empty($this->notif)) {
			return true;
		}
		
		# Error in removing
		return $this->notif;
	}
	
	/**
	* Remove marked image
	* Remove image in a mark
	* 
	* @access public
	* @param string $markID ID of mark
	* @param string $imgID ID of image
	*
	* @param mixed True on success, info on failure
	*/
	public function removeImg($markID, $imgID) {
		$del = "DELETE FROM MarkImgs WHERE PID='{$markID}' AND ImgID2='{$imgID}'";
		
		# Remove image assoc. with mark 
		if(!$this->mysqli->query($del)) {
			$this->notif = "ERROR: delete rsrc-img <br/>";
		}
		
		# Removed successfully
		if(empty($this->notif)) {
			return true;
		}
		
		# Error in removing
		return $this->notif;
	}
	
	/**
	* Share resource
	* Share a resource with an in area
	* 
	* @access public
	* @param string $id Resource ID
	* @param string $title Title
	* @param string $notes Notes
	* @param array $links Links
	* @param array $files Files
	* @param array $coeds Coeditors
	* @param string $categ Category
	* @param string $visib Visibility
	*
	* @param mixed ID on success, false on failure
	*/
	public function share($id, $title, $notes, $links, $refs, $files, $coeds, $categ, $visib) {
		# Create new resource
		$rsrcID = $this->create($title, $notes, $links, $refs, $files, $coeds, $categ, $visib);
		
		$ins = "INSERT INTO {$this->table} VALUES ('{$id}', '{$rsrcID}', '0', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
		
		# Append resource to area
		if(!$this->mysqli->query($ins)) {
			$this->notif[] = "ERROR: insert area-rsrc";
		}
		
		# Appended successfully
		if(empty($this->notif)) {
			return $rsrcID;
		}
		
		# Error occurred
		//echo '<pre>', var_dump($this->notif), '</pre>';
		return false;
	}
	
	/**
	* Fetch resources
	* Fetch resources associated with an area
	* 
	* @access public
	* @param string $id ID of area
	* @param int $start Start of return results
	*
	* @return boolean True on success, false on failure
	*/
	public function fetch($id, $start) {
		switch($this->area) {
			# Microorganisms
			case 'micro':
				# Find all marked microorganisms
				$sel = "
					SELECT T1.* FROM Images AS T1 INNER JOIN MarkMicros AS T2
					ON T2.MicroID='{$id}' AND T1.ID=T2.ImgID ORDER BY T2.CrtOn LIMIT {$start}, 10
				";
				
				# Found
				if(($res = $this->mysqli->query($sel)) and !empty($res->num_rows)) {
					while($img = $res->fetch_object()) { ?>
						<span class="img">
							<a href="main.php?img=view&id=<?php echo $img->ID ?>">
							<img class="stage file locked ghost" src="<?php echo $img->Thumb ?>" alt="<?php echo $img->Title ?>" style="width:<?php echo (125/$img->Height)*$img->Width ?>px"
								data-id="<?php echo $img->ID ?>" data-src="<?php echo $img->Path ?>" data-visib="<?php echo $img->Visib ?>" data-categ="<?php echo $img->Categ ?>"
								data-tool="{'head':'<span class=\'permalink\'><a href=\'main.php?img=view&id=<?php echo $img->ID ?>\' target=\'_blank\'><?php echo $img->Title ?></a></span>','stay':'true','x':'l'}"/></a>
							<div class="ctrl-img none">
								<div class="ctrl-main">
									<input name="pic" class="def-img abled" type="checkbox" value="<?php echo $img->Thumb ?>" id="pic<?php echo $img->ID ?>"/> <label for="pic<?php echo $img->ID ?>">Default</label>
									<input name="rimg[]" class="rmv-img abled" type="checkbox" value="<?php echo $img->ID ?>" id="rimg<?php echo $img->ID ?>"/> <label for="rimg<?php echo $img->ID ?>">Remove</label>
								</div>
							</div>
						</span> <?php
					}
					
					return true;
				}
			break;
			
			# Marks
			case 'mark':
				# Find all marks
				$sel = "
					SELECT T1.* FROM Images AS T1 INNER JOIN Marks AS T2
					ON T1.ID=T2.ImgMarkID AND T2.ImgID='{$id}' ORDER BY T2.CrtOn LIMIT {$start}, 10
				";
				
				# Found
				if(($res = $this->mysqli->query($sel)) and !empty($res->num_rows)) {
					while($img = $res->fetch_object()) { ?>
						<span class="img">
							<a href="main.php?img=view&id=<?php echo $img->ID ?>">
							<img class="stage file locked ghost" src="<?php echo $img->Thumb ?>" alt="<?php echo $img->Title ?>" style="width:<?php echo (125/$img->Height)*$img->Width ?>px"
								data-id="<?php echo $img->ID ?>" data-src="<?php echo $img->Path ?>" data-visib="<?php echo $img->Visib ?>" data-categ="<?php echo $img->Categ ?>"
								data-tool="{'head':'<span class=\'permalink\'><a href=\'main.php?img=view&id=<?php echo $img->ID ?>\' target=\'_blank\'><?php echo $img->Title ?></a></span>','stay':'true','x':'l'}"/></a>
							<div class="ctrl-img none">
								<div class="ctrl-main">
									<input name="pic" class="def-img abled" type="checkbox" value="<?php echo $img->Thumb ?>" id="pic<?php echo $img->ID ?>"/> <label for="pic<?php echo $img->ID ?>">Default</label>
									<input name="rimg[]" class="rmv-img abled" type="checkbox" value="<?php echo $img->ID ?>" id="rimg<?php echo $img->ID ?>"/> <label for="rimg<?php echo $img->ID ?>">Remove</label>
								</div>
							</div>
						</span> <?php
					}
					
					return true;
				}
			break;
			
			# Links
			case 'link':
				# Find all links
				$sel = "
					SELECT * FROM RsrcLinks WHERE PID='{$id}' ORDER BY CrtOn LIMIT {$start}, 10
				";
				
				# Found
				if(($res = $this->mysqli->query($sel)) and !empty($res->num_rows)) { ?>
					<span class="none"> <?php
						while($link = $res->fetch_object()) { ?>
							<li class="link">
								<a href="<?php echo $link->Link ?>"><?php echo Tool::truncate($link->Link, 70) ?></a>
								<button type="button" class="remove icon read" data-area="link" data-id="<?php echo $link->CID ?>"></button>
							</li> <?php
						} ?>
					</span> <?php
					
					return true;
				}
			break;
			
			# Resources
			default:
				# Find all resources
				$sel = "
					SELECT T1.* FROM Resources AS T1 INNER JOIN {$this->table} AS T2
						ON T1.ID=T2.CID WHERE T2.PID='{$id}' ORDER BY T2.CrtOn LIMIT {$start}, 10
				";
				
				# Found
				if(($resRsrc = $this->mysqli->query($sel)) and !empty($resRsrc->num_rows)) { ?>
					<span class="none"> <?php
						while($rsrc = $resRsrc->fetch_object()) { ?>
							<li class="rsrc">
								<a href="main.php?rsrc=view&id=<?php echo $rsrc->ID ?>"><?php echo $rsrc->Title ?></a>
								<button type="button" class="remove icon read" data-area="<?php echo $this->area ?>" data-id="<?php echo $rsrc->ID ?>"></button>
							</li> <?php
						} ?>
					</span> <?php
					
					return true;
				}
			break;
		}
		
		return false;
	}
	
	/**
	* Append links
	* Append links associated to that area
	* 
	* @access public
	* @param string $id ID of area
	* @param array $links Links to be appended
	* 
	* @return boolean True on success, false on failure
	*/
	public function appendLink($id, $links) {
		# Iterate through each links
		foreach($links as $link) {
			if(empty($link) or $link=='http://') {
				continue;
			}
			
			$linkID = Tool::generateID('link');
			$link = Tool::trimout($link);
			
			# Append links
			$ins = "
				INSERT INTO RsrcLinks VALUES (
					'{$id}', '{$linkID}', '".mysql_real_escape_string($link)."', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."'
				)
			";
			
			# Append links in database
			if(!$this->mysqli->query($ins)) {
				$this->notif[] = "ERROR: ins rsrc link";
				return false;
			}
		}
		
		return true;
	}
	
	/**
	* Remove links
	* Remove links associated to that area
	* 
	* @access public
	* @param string $id ID of area
	* @param array $linkID IDs of links to be appended
	* 
	* @return boolean True on success, false on failure
	*/
	public function removeLink($id, $linkID) {
		# Remove link assoc. with an area
		$del = "DELETE FROM RsrcLinks WHERE PID='{$id}' AND CID IN ('".implode("', '", $linkID)."')";
		
		if(!$this->mysqli->query($del)) {
			# Error occurred
			$this->notif[] = "ERROR: del rsrc link";
			return false;
		}
		
		# Successfully removed
		return true;
	}
	
	/**
	* Display all resources
	* Retrieve all contents of resources on a page
	* 
	* @access public
	* @param array $queries IDs of resources
	*/
	public function displayAll($queries, $opts) { ?>
		<output> <?php
			if($results = $this->search($queries, $opts, 0, 10)) {
				while($result = $results[0]->fetch_object()) {
					$this->displayContent($result, false);
				}
			} ?>
		</output> <?php
	}
	
	/**
	* Guess resources
	* Provides a list of resources (guess) on user input
	* Makes selection of resource and id faster
	* 
	* @access public
	*/
	public function guess($query) {
		# Search for locations matching the query string and constrains passed
		$rsrcs = $this->search($query, $_REQUEST, 0, 10);
		
		# Location is not found
		if(!$rsrcs or empty($rsrcs[1])) {
			return false;
		}
		
		while($rsrc = $rsrcs[0]->fetch_object()) { ?>
			<div class="guess rsrc" data-id="<?php echo $rsrc->ID ?>" data-value="<?php echo $rsrc->Title ?>" tabindex="0"
				<?php if(strlen($rsrc->Title) > 50) { ?> data-tool="{'head':'<?php echo $rsrc->Title ?>'}" <?php } ?>>
				<a href="main.php?rsrc=view&id=<?php echo $rsrc->ID ?>"> <?php
					echo Tool::truncate($rsrc->Title, 50); ?></a>
			</div> <?php
		}
		
		if($_REQUEST['s']=='true') { ?>
			<div class="guess-header rsrc query">
				<a href="main.php?rsrc=view&q=<?php echo urlencode($query) ?>" target="_blank" title="<?php echo $query ?>"><?php echo Tool::truncate($query, 30) ?></a>
				<span class="right bold none" title="<?php echo ($found = $rsrcs[0]->num_rows.' of '.$rsrcs[1]).' items found' ?>"><?php echo $found ?></span>
			</div> <?php
		}
	}
	
	/**
	* Retrieve details
	* Get all details associated with resource to be displayed
	* 
	* @access private
	* @param string $area Area where resource is associated
	* @param string $id ID of resource
	* 
	* @return mixed Returned results on search
	*/
	private function retrieve($area, $id) {
		$selSize = "SELECT FOUND_ROWS()";
		
		switch($area) {
			# Microorganisms
			case 'micro':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Microorganisms AS T1 INNER JOIN MicroRsrcs AS T2
						ON T1.ID=T2.PID AND T2.CID='{$id}' AND T1.Remove='0' ORDER BY T2.CrtOn LIMIT 10
				";
			break;
			
			# Projects
			case 'proj':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Projects AS T1 INNER JOIN ProjRsrcs AS T2
						ON T1.ID=T2.PID AND T2.CID='{$id}' AND T1.Remove='0' ORDER BY T2.CrtOn LIMIT 10
				";
			break;
			
			# Images
			case 'img':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Images AS T1 INNER JOIN RsrcImgs AS T2
						ON T1.ID=T2.CID AND T2.PID='{$id}' AND T1.Remove='0' ORDER BY T2.CrtOn LIMIT 10
				";
			break;
			
			# Documents
			case 'doc':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS DISTINCT T1.* FROM Documents AS T1 INNER JOIN RsrcDocs AS T2
						ON T1.ID=T2.CID AND T2.PID='{$id}' AND T1.Remove='0' ORDER BY T2.CrtOn LIMIT 10
				";
			break;
			
			# Links
			case 'link':
				$sel = "
					SELECT SQL_CALC_FOUND_ROWS * FROM RsrcLinks WHERE PID='{$id}' ORDER BY CrtOn LIMIT 10
				";
			break;
		}
		
		# Find in database
		$res = $this->mysqli->query($sel);
		$size = $this->mysqli->query($selSize);
		$size = $size->fetch_row();
		
		# Return results and size of results
		return array($res, $size[0]);
	}
	
	/**
	* Display main location stage
	* List all resources in the main page
	* 
	* @access public
	* @param mixed $rsrcs List of resources from returned search results
	* @param integer $size Size of rows from returned search results
	* @param string $query Query string that was searched for
	* @param array $opts Optional parameters
	* @param integer $start Starting row in mysql returned results
	*/
	public function displayMain($rsrcs, $size, $query, $opts, $start) {
		# One resource to be viewed
		$view = $rsrcs->num_rows==1;
		# Page number
		$page = ceil(($start+1)/10);
		# Process URL params
		$optstr = Tool::optstrify($opts); ?>
		
		<div id="side">
			<div id="navis"> <?php
				# Links to previous ten items ?>
				<a href="main.php?<?php echo $optstr.(empty($query) ? '' : '&q='.$query).(empty($start) ? '&s=0' : '&s='.(intval($start)-10)) ?>"
					class="navi ui ui-button prev <?php if(empty($start)) echo 'disabled' ?>" tabindex="-1" title="Previous 10 items"></a> <?php
				# Links to next ten items ?>
				<a href="main.php?<?php echo $optstr.(empty($start) ? '&s=10' : '&s='.(intval($start)+10)) ?>"
					class="navi ui ui-button next <?php if(($rsrcs->num_rows<10) or ($rsrcs->num_rows*$page)>=$size) { echo 'disabled'; } ?>" tabindex="-1" title="Next 10 items"></a>
			</div> <?php
			
			# Knobs to stage resource ?>
			<div id="knobs"> <?php $i = 1;
				while($rsrc = $rsrcs->fetch_object()) {
					$title = Tool::truncate($trtitle = $rsrc->Title, 80); ?>
					
					<div id="knob<?php echo $rsrc->ID ?>" class="knob rsrc <?php if($view) echo "lock"?>" data-query="<?php echo $rsrc->ID ?>"
						data-id="<?php echo $rsrc->ID ?>" data-tool="{'head':'<b class=\'cool\'><?php echo $title ?></b>','x':'l'}">
						<?php echo $i++ ?>
					</div> <?php
				} ?>
			</div>
		</div> <?php
		
		# Labels stage items ?>
		<div id="hnotif" class="escape"> <?php
			# Shows metadata of all searched items ?>
			<span id="query" class="escape iblock" data-tool="{'head':'<?php echo ($all = (empty($query) and empty($opts['q']))) ? "All resources" : (empty($opts['q']) ? $trtitle : $opts['q']) ?>','x':'l'}"
				<?php if(!($nctrl = empty($_COOKIE['ctrl']['search']))) { echo 'style="width:400px"'; } ?>>
				<?php echo ($all ? "All resources" : ($view ? $title : $query)) ?>
			</span>
			
			<span>
				<span id="search-ctrls" <?php if($nctrl) { echo 'class="none"'; } ?>> <?php
					# No. of returned results
					echo '<span id="numresults">Showing '.($rsrcs->num_rows).' of <b>'.$size.'</b> result(s)</span> on page ';
					
					# Many microorganisms are to be viewed
					$ob = isset($_REQUEST['ob']); $of = true;
					unset($opts['ob']); unset($opts['oa']);
					$optstr = Tool::optstrify($opts);
					
					# Prepare filter options and page selector ?>
					<select id="main-page" class="page navi" data-tool="{'head':'Page'}"> <?php
						for($i=0, $x=$size/10; $i<$x; $i++)	echo "<option ".((isset($opts['s']) and $opts['s']==($i*10)) ? 'selected="selected"' : '').'value="main.php?'.$optstr.(empty($query) ? '' : '&q='.$query).'&s='.($i*10).'">'.($i+1).'</option>';?>
					</select> sorted by <?php
					
					# Prepare filter options ?>
					<select class="navi" data-tool="{'head':'Sort'}">
						<option value="main.php?<?php echo $optstr ?>&ob=title&oa=asc" <?php if($ob and $_REQUEST['ob']=='title') { echo 'selected="selected"'; $of = false; } ?>>Title</option>
						<option value="main.php?<?php echo $optstr ?>&ob=notes&oa=asc" <?php if($ob and $_REQUEST['ob']=='notes') { echo 'selected="selected"'; $of = false; } ?>>Notes</option>
						<option value="main.php?<?php echo $optstr ?>&ob=crtby&oa=asc" <?php if($ob and $_REQUEST['ob']=='crtby') { echo 'selected="selected"'; $of = false; } ?>>Author</option>
						<option value="main.php?<?php echo $optstr ?>&ob=updon&oa=desc" <?php if($ob and $_REQUEST['ob']=='updon') { echo 'selected="selected"'; $of = false; } ?>>Last edited</option>
						<option value="main.php?<?php echo $optstr ?>&ob=shron&oa=desc" <?php if($ob and $_REQUEST['ob']=='shron') { echo 'selected="selected"'; $of = false; } ?>>Last shared</option>
						<option value="main.php?<?php echo $optstr ?>&ob=crton&oa=desc" <?php if($ob and $_REQUEST['ob']=='crton') { echo 'selected="selected"'; $of = false; } ?>>Date created</option>
						<option value="main.php?<?php echo $optstr ?>&ob=id&oa=asc" <?php if($ob and $_REQUEST['ob']=='id') { echo 'selected="selected"'; $of = false; } ?>>ID</option>
					</select>
				</span>
				<span <?php if(!$nctrl) { echo 'class="none"'; } ?>><?php echo "$rsrcs->num_rows of <b>$size</b> result(s) on page <b>$page</b>";  ?></span> <button type="button" class="navi-details <?php echo (!$nctrl ? 'selected' : '') ?>" data-tool="{'head':'Search controls'}"></button>
			</span>
		</div> <?php
		
		# Contains all location headers ?>
		<div id="stage"> <?php
			$rsrcs->data_seek(0);
			while($rsrc = $rsrcs->fetch_object()) {
				$this->displayHeading($rsrc, $view ? true : false);
			} ?>
		</div> <?php
	}
	
	/**
	* Display a resource heading
	* Displays a heading for each resource in the results
	* which contains the resource's title
	* 
	* @access public
	* @param mixed $rsrc Contains all details of the resource
	* @param boolean $cont Checks if content is to be displayed too
	*/
	public function displayHeading($rsrc, $cont) {
		# List a resource first as an area with a header that can be selected/clicked by the user in the stage
		# Data included: head (title), id (resource id)
		?> <div id="area<?php echo $rsrc->ID ?>" class="stage area rsrc" data-head="<?php echo $rsrc->Title ?>">
			<div class="div-header rsrc <?php echo $cont ? "active lock" : "heading" ?>" data-id="<?php echo $rsrc->ID ?>" data-content="rsrc"
				<?php if(strlen($rsrc->Title)>100) echo 'data-tool="{\'head\':\''.$rsrc->Title.'\',\'x\':\'l\'}"' ?>>
				<a href="main.php?rsrc=view&id=<?php echo $rsrc->ID ?>" class="title" tabindex="-1">
					<?php echo Tool::truncate($rsrc->Title, 100) ?></a>
			</div> <?php
			
			# Show resource's contents if necessary
			if($cont) {
				$this->displayContent($rsrc, $cont);
			} ?>
		</div> <?php
	}
	
	/**
	* Display contents of resource
	* Displays the contents of a resource, from its title
	* to its associated items in other areas of the system
	* 
	* @access public
	* @param mixed $rsrc Contains all details of the resource
	* @param boolean $cont Checks if only one resource is found in results
	*/
	public function displayContent($rsrc, $cont) {
		?> <div class="div-content">
			<form id="form-rsrc<?php echo $rsrc->ID ?>" class="rsrc" name="form-rsrc" method="post" action="process.php?rsrc=edit" enctype="multipart/form-data" novalidate="novalidate">
			<div class="div-upper">
				<div class="div-body">
					<div class="div-peel title"><b>Title</b></span></div>
					<div class="div-case">
						<textarea name="title" class="title reqd read" readonly="readonly" rows="<?php echo ceil(strlen($rsrc->Title)/80) ?>"><?php echo $rsrc->Title ?></textarea>
					</div>
					
					<div class="div-peel peel <?php echo ($empty = (empty($rsrc->Notes) or $rsrc->Notes=='NULL')) ? "on" : "off open" ?> next notes"><b>Notes</b></div>
					<div class="div-case <?php if($empty) echo "none" ?>">
						<textarea name="notes" rows="<?php echo empty($rsrc->Notes) ? '5' : ceil(strlen($rsrc->Notes)/100) ?>" class="read reqd" readonly="readonly"><?php echo $rsrc->Notes ?></textarea><br/>
					</div> <?php 
					
					//LINKS/////////////////////////////////////////////////////////////////////////////////////////////////////
					
					list($resLink, $sizeLink) = $this->retrieve('link', $rsrc->ID); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeLink)) ? "on" : "off open" ?> next link"><b>Links</b></div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) { ?>
							<ol class="link"> <?php
								while($link = $resLink->fetch_object()) { ?>
									<li class="link">
										<a href="<?php echo (strpos($link->Link, 'http://')>=0) ? $link->Link : 'http://'.$link->Link ?>" target="_blank"><?php echo Tool::truncate($link->Link, 70) ?></a>
										<button type="button" class="remove icon read" data-area="link" data-id="<?php echo $link->CID ?>"></button><br/>
									</li> <?php
								} ?>
							</ol>
							<a class="fetch link tick" data-area="link" data-id="<?php echo $rsrc->ID ?>" data-start="10">Show more</a> <?php
						} ?>
						
						<div class="none">
							<div class="default">
								<input name="link[]" type="text" class="link" value="http://"/>
								<button class="append icon" type="button"></button>
							</div>
							<div class="links"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div> <?php 
					
					//IMAGES/////////////////////////////////////////////////////////////////////////////////////////////////////
					
					list($resImg, $sizeImg) = $this->retrieve('img', $rsrc->ID); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeImg)) ? "on" : "off open" ?> next img">
						<b>Images</b> <span><?php echo $sizeImg ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!empty($sizeImg)) {
							while($img = $resImg->fetch_object()) { ?>
								<span class="img">
									<a href="main.php?img=view&id=<?php echo $img->ID ?>">
									<img class="stage file locked ghost" src="<?php echo $img->Thumb ?>" alt="<?php echo $img->Title ?>" style="width:<?php echo (125/$img->Height)*$img->Width ?>px"
										data-id="<?php echo $img->ID ?>" data-src="<?php echo $img->Path ?>" data-visib="<?php echo $img->Visib ?>" data-categ="<?php echo $img->Categ ?>"
										data-tool="{'head':'<span class=\'permalink\'><a href=\'main.php?img=view&id=<?php echo $img->ID ?>\' target=\'_blank\'><?php echo $img->Title ?></a></span>','stay':'true','x':'l'}"/></a>
									<div class="ctrl-img none">
										<div class="ctrl-main">
											<input name="pic" class="def-img abled" type="checkbox" value="<?php echo $img->Thumb ?>" id="pic<?php echo $img->ID ?>"/> <label for="pic<?php echo $img->ID ?>">Default</label>
											<input name="rimg[]" class="rmv-img abled" type="checkbox" value="<?php echo $img->ID ?>" data-area="micro" id="rimg<?php echo $img->ID ?>"/> <label for="rimg<?php echo $img->ID ?>">Remove</label>
										</div>
									</div>
								</span> <?php
							} ?> <span class="imgs"></span>
							<a class="fetch img tick" data-area="rsrc" data-id="<?php echo $micro->ID ?>" data-start="10">Show more</a> <?php
						} ?>
						
						<div class="none">
							<div class="default">
								<input name="img[val][]" class="img" type="text" placeholder="Image title" data-guess="img=guess"/>
								<button class="append icon" type="button" data-area="img" data-id="0"></button>
								<input name="img[id][]" type="hidden" class="abled">
							</div>
							<div class="imgs"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div> <?php 
					
					//DOCUMENTS/////////////////////////////////////////////////////////////////////////////////////////////////////
					
					list($resDoc, $sizeDoc) = $this->retrieve('doc', $rsrc->ID); ?>
					
					<div class="div-peel peel <?php echo ($empty = empty($sizeDoc)) ? "on" : "off open" ?> next doc">
						<b>Documents</b> <span><?php echo $sizeDoc ?></span>
					</div>
					<div class="div-case <?php if($empty) echo "none" ?>"> <?php
						if(!$empty) { ?>
							<ol> <?php
								while($doc = $resDoc->fetch_object()) { ?>
									<li class="doc">
										<a href="main.php?doc=view&id=<?php echo $doc->ID ?>" data-tool="{'head':'<?php echo $doc->Title ?>','x':'l'}"><?php echo Tool::truncate($doc->Title, 80) ?></a>
										<button class="small" data-title="<?php echo $doc->Title ?>" data-doc="<?php echo $doc->Path ?>">Open</button>
										<button type="button" class="remove icon read" data-area="doc" data-id="<?php echo $doc->ID ?>"></button><br/>
									</li> <?php
								} ?>
								<a class="fetch doc tick" data-area="rsrc" data-id="<?php echo $rsrc->ID ?>" data-start="10">Show more</a>
							</ol> <?php
						} ?>
						
						<div class="none">
							<div class="default">
								<input type="text" class="doc" name="doc[val][]" placeholder="Document title" data-guess="doc=guess"/>
								<button class="append icon" type="button" data-area="doc" data-id="0"></button>
								<input type="hidden" name="doc[id][]" class="abled"/>
							</div>
							<div class="docs"></div>
						</div>
						<button type="button" class="addmore peel on prev read" data-on="Add" data-off="Cancel">Add</button>
					</div>
					
					<div class="div-peel peel <?php echo ($empty = (empty($rsrc->Ref) or $rsrc->Ref=='NULL')) ? "on" : "off open" ?> next ref">
						<b>References</b></div>
					<div class="div-case <?php if($empty) echo "none" ?>">
						<textarea name="ref" rows="<?php echo $empty ? '3' : ceil(strlen($rsrc->Ref)/100) ?>" class="read abled" readonly="readonly"> <?php
							echo $rsrc->Ref ?></textarea>
					</div> <?php
					
					//FILES////////////////////////////////////////////////////////////////////////////////////////////////////////////// ?>
					
					<div class="div-peel peel on next file none"><b>Files</b></div>
					<div class="div-case none">
						<input type="file" name="file[]" multiple="multiple" accept="image/jpeg,image/gif,application/pdf"/>
					</div> <?php
					
					//SETTINGS////////////////////////////////////////////////////////////////////////////////////////////////////////////*/ ?>
					
					<div class="div-peel peel on next safe none"><b>Settings</b><span class="setting help"></span></div>
					<div class="div-case none safe"></div>
				</div>
				
				<div class="div-head">
					<img class="default ghost" src="<?php echo empty($rsrc->ImgPath) ? "template/rsrc.png" : "process.php?img=open&deg=20&path={$rsrc->ImgPath}" ?>" alt="<?php echo $rsrc->Title ?>"/>
					
					<div class="controls">
						<button class="details dial" type="button" data-area="rsrc" data-id="<?php echo $rsrc->ID ?>" data-name="<?php echo $rsrc->Title ?>"><span>Details</span></button>
						
						<button class="stat dial peel on next" type="button"><b>Contents</b></button>
						<ul class="metas none">
							<li class="meta">Links <span><?php echo $sizeLink ?></span></li>
							<li class="meta">Images <span><?php echo $sizeImg ?></span></li>
							<li class="meta">Documents <span><?php echo $sizeDoc ?></span></li>
						</ul> <?php
						
						$sett = new Setting('rsrc', null, $this->mysqli, $this->user);
						$verified = $sett->verify($rsrc->ID);
						
						if($verified) { ?><hr/>
							<button class="edit dial" data-area="rsrc" data-id="<?php echo $rsrc->ID ?>" type="reset"><span>Edit</span></button> <?php
						} ?>
					</div>
				</div>
				
				<div class="div-mind">
					<input name="q" type="hidden" class="id abled" value="<?php echo $rsrc->ID ?>"/>
					<input name="id" type="hidden" class="abled" value="<?php echo $rsrc->ID ?>"/>
					<input name="upd" type="checkbox" class="abled none" value="<?php echo $rsrc->ID ?>"/>
					<input name="recov" type="checkbox" class="recov abled" value="<?php echo $rsrc->ID ?>"/>
					<input name="del" type="checkbox" class="del abled none" value="<?php echo $rsrc->ID ?>"/>
				</div>
			</div>
			
			<div class="div-dial"> <?php
				if($rsrc->Remove=='0') { ?>
					<button class="delete tick read left" type="button" form="form-rsrc<?php echo $rsrc->ID ?>" data-area="rsrc">Delete</button> <?php
				}
				else { ?>
					<button class="recover tick read left" type="button" form="form-rsrc<?php echo $rsrc->ID ?>" data-area="rsrc">Recover</button> <?php
				} ?>
				<button type="button" form="form-rsrc<?php echo $rsrc->ID ?>" class="cancel edit read">Cancel</button>
				<button type="submit" class="read">Update</button> <?php
				
				if(!$cont) { ?>
					<button type="button" class="close-content reset">Close</button> <?php
				} ?>
			</div>
			</form>
		</div> <?php
	}
}

?>